// 请求工具函数
import { showToast } from 'vant';

interface RequestOptions {
  url: string;
  method: 'GET' | 'POST' | 'PUT' | 'DELETE';
  data?: any;
  params?: any;
  headers?: Record<string, string>;
}

// 创建请求函数
export const request = async (options: RequestOptions) => {
  const { url, method, data, params, headers = {} } = options;
  
  // 默认请求头
  const defaultHeaders = {
    'Content-Type': 'application/json',
    ...headers
  };
  
  // 构建请求参数
  const requestOptions: RequestInit = {
    method,
    headers: defaultHeaders,
    credentials: 'include' // 携带cookie
  };
  
  // 添加请求体
  if (data) {
    requestOptions.body = JSON.stringify(data);
  }
  
  // 处理GET请求参数
  let requestUrl = url;
  if (params) {
    const queryString = Object.entries(params)
      .map(([key, value]) => `${key}=${encodeURIComponent(String(value))}`)
      .join('&');
    requestUrl = `${url}${url.includes('?') ? '&' : '?'}${queryString}`;
  }
  
  try {
    const response = await fetch(requestUrl, requestOptions);
    
    // 调试：打印响应头信息（特别是Set-Cookie）
    if (requestUrl.includes('/login')) {
      console.log('=== 登录请求响应头调试 ===');
      console.log('响应状态:', response.status);
      console.log('当前页面URL:', window.location.href);
      console.log('请求URL:', requestUrl);
      
      // 检查响应头
      console.log('响应头:');
      let hasSetCookie = false;
      response.headers.forEach((value, key) => {
        console.log(`  ${key}: ${value}`);
        if (key.toLowerCase() === 'set-cookie') {
          hasSetCookie = true;
          console.log('*** 发现Set-Cookie头 ***:', value);
          // 分析Set-Cookie属性
          const cookieAttributes = value.split(';').map(attr => attr.trim());
          console.log('Cookie属性分析:');
          cookieAttributes.forEach((attr, index) => {
            if (index === 0) {
              console.log(`  主体: ${attr}`);
            } else {
              console.log(`  属性: ${attr}`);
              if (attr.toLowerCase().includes('httponly')) {
                console.log('    ⚠️ 检测到HttpOnly属性 - JavaScript无法访问此cookie');
              }
              if (attr.toLowerCase().includes('samesite')) {
                console.log(`    ⚠️ SameSite策略: ${attr}`);
              }
              if (attr.toLowerCase().includes('domain')) {
                console.log(`    ⚠️ Domain限制: ${attr}`);
              }
              if (attr.toLowerCase().includes('path')) {
                console.log(`    ⚠️ Path限制: ${attr}`);
              }
            }
          });
        }
      });
      
      if (!hasSetCookie) {
        console.log('❌ 未发现Set-Cookie头 - 服务器可能没有设置cookie');
        console.log('💡 建议检查服务器端登录接口是否正确设置refreshToken cookie');
      }
      
      // 检查浏览器cookie存储情况
      console.log('\n=== Cookie存储检查 ===');
      console.log('响应处理前的document.cookie:', document.cookie || '(空)');
      
      // 延迟检查cookie，确保浏览器有时间处理Set-Cookie头
      setTimeout(() => {
        console.log('\n=== 延迟Cookie检查 (100ms后) ===');
        console.log('响应处理后的document.cookie:', document.cookie || '(空)');
        
        // 详细分析cookie
        if (document.cookie) {
          const cookies = document.cookie.split(';').map(c => c.trim()).filter(c => c);
          console.log(`发现 ${cookies.length} 个cookie:`);
          cookies.forEach((cookie, index) => {
            const [name, value] = cookie.split('=');
            console.log(`  ${index + 1}. ${name} = ${value || '(空值)'}`);
          });
          
          // 查找refreshToken
          const refreshTokenCookie = cookies.find(cookie => 
            cookie.startsWith('refreshToken=')
          );
          if (refreshTokenCookie) {
            console.log('✅ 找到refreshToken cookie:', refreshTokenCookie);
          } else {
            console.log('❌ 未找到refreshToken cookie');
          }
        } else {
          console.log('❌ document.cookie为空');
        }
        
        // 提供调试建议
        console.log('\n=== 调试建议 ===');
        console.log('1. 打开浏览器开发者工具 -> Network面板');
        console.log('2. 重新登录，查看登录请求的Response Headers');
        console.log('3. 检查是否有Set-Cookie: refreshToken=...');
        console.log('4. 如果有Set-Cookie但cookie仍为空，可能是HttpOnly或跨域问题');
        console.log('5. 也可以查看Application面板 -> Cookies查看实际存储情况');
      }, 100);
      
      console.log('=== 响应头调试结束 ===');
    }
    
    const responseData = await response.json();
    
    // 处理响应状态
    if (response.ok) {
      return responseData;
    } else {
      // 处理业务错误
      showToast(responseData.message || '请求失败');
      return Promise.reject(responseData);
    }
  } catch (error) {
    // 处理网络错误
    showToast('网络异常，请稍后重试');
    return Promise.reject(error);
  }
};